package cn.sciento.transfer.infra.datasource.sql;

import com.google.common.base.CaseFormat;
import io.choerodon.mybatis.domain.EntityColumn;
import io.choerodon.mybatis.domain.EntityField;
import io.choerodon.mybatis.domain.EntityTable;
import io.choerodon.mybatis.helper.EntityHelper;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

public class FieldBuilder {
  public static <T> List<EntityField> buildFieldInDB(T entity) {
    EntityTable entityTable = EntityHelper.getEntityTable(entity.getClass());
    return entityTable.getEntityClassColumns().parallelStream()
      .filter(item -> (item.isInsertable() || item.isUpdatable()))
      .map(EntityColumn::getField).collect(Collectors.toList());
  }
  
  public static <T> List<String> buildFieldName(T entity, List<EntityField> entityFieldList) {
    List<String> fieldList = (List<String>)entityFieldList.parallelStream().map(EntityField::getName).collect(Collectors.toList());
    return fieldList;
  }
  
  public static <T> List<Object> buildFieldValue(T entity, List<EntityField> entityFieldList) {
    List<Object> fieldValueList = (List<Object>)entityFieldList.parallelStream().map(item -> item.get(entity)).collect(Collectors.toList());
    return fieldValueList;
  }
  
  public static String formatFieldToColumn(String fieldName) {
    if (StringUtils.isAllUpperCase(fieldName))
      return fieldName; 
    if (!fieldName.contains("_"))
      return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName); 
    return fieldName;
  }
}
